package com.credit.util;

import java.util.Random;
import java.util.concurrent.TimeUnit;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.credit.service.RedisService;


/**
 * 发送验证码
 * @Title: SendVerifyCodeCase.java
 * @Description: 
 * @author wangxuechuan
 * @date 2015年12月8日下午1:45:05
 * @version V1.0   
 *
 */
public class SendVerifyCodeCase  {
	
	private static final Log log = LogFactory.getLog(SendVerifyCodeCase.class);
	
	
	public SendVerifyCodeCase(){
	}


	
	/**
	 * 生成手机或者邮箱注册验证码
	 * 
	 * @param account
	 * @return
	 */
	public static String genRegisterVerifyCode(String prefix,String account) {
/*		String key = prefix+":" + account; 
		String verify_code = "";
		Random r = new Random();
		verify_code = String.valueOf(100000 + r.nextInt(900000));
		
		log.info("账号为 [ "+account+" ]生成的手机验证码为 [ "+verify_code+" ]");
		
		RedisService redisService = (RedisService) ApplicationContextUtils.getBean("redisService");
		
		redisService.delete(key);
		
		redisService.setValueDefaultNull(key, verify_code, 10, TimeUnit.MINUTES);
		
		return verify_code;*/
		
		Random r = new Random();
		String verify_code = String.valueOf(100000 + r.nextInt(900000));
		
		return genRegisterVerifyCode(prefix,account,verify_code);
		
	}
	
	/**
	 * 生成手机或者邮箱注册验证码
	 * 
	 * @param account
	 * @return
	 */
	public static String genRegisterVerifyCode(String prefix,String account,String code) {
		String key = prefix+":" + account; 
		String verify_code = "";
		Random r = new Random();
		verify_code = code;
		
		log.info("账号为 [ "+account+" ]生成的"+ParamsConstant.CODE_NAME_MAP.get(prefix)+"验证码为 [ "+verify_code+" ]");
		
		RedisService redisService = (RedisService) ApplicationContextUtils.getBean("redisService");
		
		redisService.delete(key);
		
		redisService.setValueDefaultNull(key, verify_code, 10, TimeUnit.MINUTES);
		
		return verify_code;
	}
	
	/**
	 * 获取注册手机或者邮箱验证码
	 * 
	 * @param account
	 * @return
	 */
	public static String getRegisterVerifyCode(String prefix,String account) {
		String key = prefix+":" + account;
		
		String verify_code = null;
		RedisService redisService = (RedisService) ApplicationContextUtils.getBean("redisService");
		try {
			
			Object object = redisService.getRealValue(key);
			if (object == null) {
				return "";
			}

			verify_code = (String) object;
		} catch (Exception e) {
			e.printStackTrace();
		}

		log.info("账号为 [ "+account+" ]获取的"+ParamsConstant.CODE_NAME_MAP.get(prefix)+"验证码为 [ "+verify_code+" ]");
		
		redisService.delete(key);
		
		return verify_code;
	}
	

}
